package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.http.HttpClientResult;
import com.antdesignbackend.backend.common.http.HttpClientUtils;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.entity.entityVo.*;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.javafx.collections.MappingChange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/remote")
public class RemoteController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();

    @Autowired
    private MeterService meterService;
    @Autowired
    private LogicService logicService;
    @Autowired
    private IShopService shopService;
    //也可以直接注入mapper来进行操作
    // @Autowired
    //userDemoMapper userDemoMapper;
    /**
     *收费录入
     */
    @GetMapping("/onoffIndex")
    @AuthToken
    public String onoffIndex() {
        // ModelAndView modelAndView = new ModelAndView("client/index");
        return "remote/onoffIndex";
    }
    /**
     *收费录入
     */
    @GetMapping("/temporaryIndex")
    @AuthToken
    public String temporaryIndex() {
        // ModelAndView modelAndView = new ModelAndView("client/index");
        return "remote/temporaryIndex";
    }
    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    public ReturnVO tableSearch(@RequestBody ShopVo data, HttpServletRequest request) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<ShopVo> datalist=new ArrayList<>();
        QueryWrapper<ShopVo> wrapper =new QueryWrapper<ShopVo>();

        //正常查询过滤条件
        if(data.getName()!=null && !data.getName().equals(""))
        {
            //  wrapper.and(wra -> wra.like("name", data.getName()).or().like("clientNo", data.getName()));
            wrapper.and(wra -> wra.like("name", data.getName()));
        }
        if(data.getPerson()!=null && !data.getPerson().equals(""))
        {
            wrapper.and(wra -> wra.like("person", data.getPerson()));
        }
        if(data.getPhone()!=null && !data.getPhone().equals(""))
        {
            wrapper.and(wra -> wra.like("phone", data.getPhone()));
        }
        if(data.getIsDue()!=null && data.getIsDue() == 0)//欠费
        {
            wrapper.and(wra -> wra.gt("dueamount",0));
        }
        if(data.getIsDue()!=null && data.getIsDue() == 1)//缴费
        {
            wrapper.and(wra -> wra.eq("dueamount",0));
        }
//        if(data.getState()!=null && !data.getState().equals(""))
//        {
//            wrapper.eq("state",data.getState());
//        }

        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=shopService.countView(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0)
        {
            datalist= shopService.searchView(wrapper.orderByAsc("name"),new Page<>(data.getPageIndex(),data.getPageSize()));

        }
        result.setData(datalist);
        return result;
    }

    /***
     * 操作相关，通过action 区分
     * @return
     */
    @PostMapping("/action")
    @ResponseBody
    @AuthToken
    public ReturnVO actions(@RequestBody LogicVo vo) throws Exception {
        result = new ReturnVO();
        boolean b = false;
        String msg=null;
        switch (vo.getAction())
        {
            case "onoff":
                //送电、断电
                try {
                  b=logicService.onOff(vo.getShopId(),vo.getOnoff(),0,0,-1);
                }catch(Exception ex)
                {
                    logger.error(ex.getMessage());
                }
                 break;
            case "reset":
                //恢复控制
                try {
                    QueryWrapper<Meter> wrappmeter = new QueryWrapper<>();
                    wrappmeter.eq("shopid", vo.shopId);
                    wrappmeter.eq("state", 1);
                    List<Meter> meterList = meterService.list(wrappmeter);
                    if (meterList.size() > 0) {
                        for (Meter item1 : meterList) {
                            item1.setModel(vo.getModel());
                           b=meterService.updateById(item1);
                        }
                    }
                } catch (Exception ex) {
                    logger.error(ex.getMessage());
                }

                break;
            case "lsonoff":
                //临时送电、断电,模式给他恢复到系统控制去
                try {
                    b=logicService.onOff(vo.getShopId(),vo.getOnoff(),0,1,-1);
                    if(b)
                     b=shopService.update(new UpdateWrapper<Shop>().set("delayTime",vo.getDelayTime()).set("delayOnOff",vo.onoff).eq("id",vo.getShopId()));
                }catch(Exception ex)
                {
                    logger.error(ex.getMessage());
                }
                break;
            default:
                break;
        }

        if(b==true){
            result.setCode("200");
            if(msg==null)
            {
                result.setMessage("保存成功！");
            }
            else
            {
                result.setMessage(msg);
            }

        }
        else
        {
            result.setCode("500");
            if(msg==null)
            {
                result.setMessage("保存失败！");
            }
            else
            {
                result.setMessage(msg);
            }

        }
        return result;
    }

}
